package com.athl.netty.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @author hl
 * @Data 2020/8/29
 * <p> 多个Buffer（Buffer数组）
 * Scattering : 将数据写入到buffer时，可以采用buffer数组.依次写入
 * Gathering : 将数据读出到buffer时。可以采用buffer数组,依次读
 */
public class ScatteringAndGatheringTest {

    /**
     * 服务端
     * byteRead=6 (六个字节)
     * position=5,limit=5
     * position=1,limit=3
     */
    public static void main(String[] args) throws Exception {
        // 使用ServerSocketChannel 和 SocketChannel 网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        // 绑定端口到socket，并启动
        serverSocketChannel.socket().bind(inetSocketAddress);
        // 创建Buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);
        // 等待客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        // 循环读取
        // 假定从客户端接受8给字节
        int msgLength = 8;
        while (true) {
            int byteRead = 0;
            while (byteRead < msgLength) {
                long l = socketChannel.read(byteBuffers);
                byteRead += l;
                System.out.println("byteRead=" + byteRead);
                Arrays.asList(byteBuffers).stream().map(buffer -> {
                    return "position=" + buffer.position() + ",limit=" + buffer.limit();
                }).forEach(System.out::println);
            }
            Arrays.asList(byteBuffers).forEach(buffer -> {
                // 将所有buffer flip
                buffer.flip();
            });
            int byteWrite = 0;
            while (byteWrite < msgLength) {
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;
                System.out.println("byteWrite=" + byteWrite);
            }
        }
    }
}
